package dragon.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dragon.oauth.jwt.JWTConfigurer;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.catalina.authenticator.SpnegoAuthenticator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@RestController
public class AdminController {

    @Autowired
    ObjectMapper objectMapper;

    @RequestMapping("/me")
    public String getUser(Authentication authentication, HttpServletRequest request) throws Exception {
        String token;
        //第一种方式获取token
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        token = details.getTokenValue();
        //第二种方式获取token
        String header = request.getHeader("Authorization");
        token = StringUtils.substringAfter(header, "bearer ");
        //token解析
        //注意，这里是需要用验证秘钥来认证token是否正确的，但是很坑的是，默认不是UTF-8的格式，因此这里要声明是UTF-8
        Claims body = Jwts.parser().setSigningKey(JWTConfigurer.JWT_SIGNING_KEY.getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();
        Object address = body.get("address");
        System.out.println("token中携带的地址信息是：" + address);
        return "good!";
    }

    @RequestMapping("/staff")
    public String getStaff() {
        return "staff!";
    }
}
